'use strict';
var bencode = require('bencode');
var P2PSpider = require('../lib');
var Parser = require('../lib/parser');
var dao = require('../lib/dao');
var p2p = P2PSpider({
    nodesMaxSize: 200, // be careful
    maxConnections: 400, // be careful
    timeout: 5000
});
var addcount = 0;
var par = new Parser();

p2p.ignore(function(infohash, rinfo, callback) {
    // false => always to download the metadata even though the metadata is exists.
    //console.log(infohash);
    //console.log(rinfo);
    //var theInfohashIsExistsInDatabase = false;
    dao.isExist(infohash, function(result) {
        //console.log(infohash + ' isexist :' + result);
        if (result) {
               dao.increaseVisit(infohash);
        }
        callback(result);
    });
});

p2p.on('metadata', function(metadata) {
    var data = par.parse(metadata);
    //console.log(metadata);
    //console.log(data);
    dao.save(data);
    addcount++;
    console.log("save success :" + addcount);
    // var torrent = JSON.parse(metadata);
    // console.log(torrent.Dict);
});

// p2p.parser=function(metadata){
//     var body ={};
//     body.address=metadata.address;
//     body.infohash=metadata.infohash;
//     body.magnet=metadata.magnet;
//     body.port=metadata.port;
// };

p2p.listen(6881, '0.0.0.0');